<?php

namespace App\Http\Controllers\Front;

use App\Models\AgricGoods;
use App\Models\Article;
use App\Models\VillagePublish;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class VillagePublishController extends Controller
{
    private $data = array();

    public function __construct(Request $request)
    {
        $this->data['pageTitle'] = '乡通-农品助力';
    }

    /**
     * 农品助力
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function index(Request $request)
    {

        $this->data['hotGoods'] = AgricGoods::pc_hot_goods_list(); // 农品热销
        $this->data['positionInfo'] = ['name' => '农品助力', 'url' => ''];
        return view('front.village_publish.index', $this->data);
    }

    /**
     * ajax农品助力列表
     * @param Request $request
     * @return array
     */
    public function ajax_village_publish_lists(Request $request)
    {
        $pagesize = $request->pagesize ?? 20;

        $publish = VillagePublish::pc_village_publish_lists([], $pagesize);

        return ajaxSuccess('获得成功', $publish);
    }

    /**
     * 农品助力详情页
     * @param Request $request
     * @param int $publishId
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function details(Request $request, $publishId = 0)
    {
        $publish = VillagePublish::with(['region_info', 'village_pub_admin_author', 'village_pub_author'])->find($publishId);

        if (empty($publish) || $publish->is_show == 0) {
            return redirect()->back();
        }

        $articles_author = [];
        if ($publish->is_admin) {
            $articles_author['id'] = $publish->village_pub_admin_author->id;
            $articles_author['name'] = $publish->village_pub_admin_author->name;
            $articles_author['avatar_url'] = $publish->village_pub_admin_author->avatar_url;
            $articles_author['fans_num'] = $publish->village_pub_admin_author->fans_num;
            $this->data['authorArticleCount'] = Article::where('admin_id', $publish->admin_id)->count();
        } else {
            $articles_author['id'] = $publish->village_pub_author->id;
            $articles_author['name'] = $publish->village_pub_author->real_name ? $publish->village_pub_author->real_name : $publish->village_pub_author->user_name;
            $articles_author['avatar_url'] = $publish->village_pub_author->head_portrait_url;
            $articles_author['fans_num'] = $publish->village_pub_author->fans_num;
            $this->data['authorArticleCount'] = Article::where('user_id', $publish->user_id)->count();
        }
        $publish['articles_author'] = $articles_author;


        $this->data['publish'] = $publish;
        $this->data['positionInfo'] = ['name' => '农品助力', 'url' => url('village_publish')];
        return view('front.village_publish.details', $this->data);
    }
}
